package com.yami.shop.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailException;
import com.alibaba.fastjson.JSONObject;
import lombok.Cleanup;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 藐视一切
 * @version 1.0
 * @date 2023/6/19 18:42
 * @description
 */
public class HuaweiOcr {

    private HttpClient httpClient;
    private HttpPost httpPost;

    public HuaweiOcr(HttpClient httpClient) {
        // 进行接口传输
        this.httpClient = httpClient;

        httpPost = new HttpPost("https://hivision-drcn.emui.hicloud.com/hivision/api/pageParse/query");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("deviceUdid", "9D6723A0DA1322EBA3383B4C311AFBCA329DB28A657A5053A48E3D6F44DD4B78");
        httpPost.setHeader("EncrypType", "PKI_TOKEN");
        httpPost.setHeader("EncryptedCode", "EncryptedCode: RXDKw4EbjSs2OajxY6BALrazCPmNZObwYWYd7TK30KVrPj5TnNTDL6R2tW+i6yZo+0vs0FT7vTq6hcsRzh6CJn/EESuuVftVl7C94PiXFTjvCSTtN8RDZABBwWDhMg/fCiee+zA56XWHW4YDl9GMcmpWTNAGmjjJ0s2uhDptFH+c3G3PQ63sPDtpcEJhEjJy2CaGoZuXalaD59ArnvoK/GY3I/uCW27H52NUhsOuG3iu+EhdFSLP1CNzLkjQDeXmd/D5LeCtOodNUobRI/YszlrAPUpGQN3wOi5LH18UQc1CalpjZL6HSCiLnkeQ1VFZpXyMIqxO/npNP61bzDS7huoY3ueDsyWJclALIgXjz7MW50ZM3pqxb3tdkQzl9zYSGSw9G8Wc5bKqEEMi3npqlrCUoXN8fFoaR3p04OV9SQySxM0auiK9P5VMfnfxyUuHOKU9F4S2epj5v22XXquikdT1Ne48hoNQPoS2Z+QlpIlkMDTqu0FKeY9UM5ps9BrB");
        httpPost.setHeader("OriginCode", "com.huawei.hitouch-810137559493278801816613610732779D6723A0DA1322EBA3383B4C311AFBCA329DB28A657A5053A48E3D6F44DD4B78");
        httpPost.setHeader("packageName", "com.huawei.hitouch");
        httpPost.setHeader("brand", "HUAWEI");
        httpPost.setHeader("EncrypTypeVersion", "type1.0");
        httpPost.setHeader("manufacturer", "HUAWEI");
        httpPost.setHeader("token", "3018fcc1-947b-4761-acb4-1f5b0c17af68_2022-08-25 15:34:45_47497A661ABC50E478C23C84C5797F92E94950C87C8E69178EA4766366DEC076");
        httpPost.setHeader("x-nuwa-trace-id", "0a43b191030279d16613610741921002");
        httpPost.setHeader("x-nuwa-span-id", "0a43b19102793310");
        httpPost.setHeader("x-nuwa-microservice-name", "APMS");
        httpPost.setHeader("Host", "hivision-drcn.emui.hicloud.com");
        httpPost.setHeader("User-Agent", "okhttp/3.14.9");
        httpPost.setHeader("Content-Type", "application/json");
    }

    public HuaweiOcr() {
        this(new DefaultHttpClient());
    }

    /**
     * 生成请求体
     * @param picBase64 图片的base64编码
     * @param width 宽度
     * @param height 高度
     * @return
     */
    private JSONObject productBody(String picBase64,int width,int height){
        JSONObject json = new JSONObject();
        json.put("appVer", "11.1.22.303");
        json.put("currency", "CNY");
        json.put("callingUid", "hitouch");
        json.put("photoWidth", width);
        json.put("photoHeight", height);
        json.put("ocrLanguage", "9");
        json.put("isConductClothing", true);
        json.put("screenScale", 3.0);
        json.put("isVerticalLayout", true);
        json.put("traceId", "ced9120d2962e4eaa7b5d6d603ec6ba8-20220825011113271");
        json.put("category", "pageParse");
        json.put("countryCode", "CN");
        json.put("deviceId", "9D6723A0DA1322EBA3383B4C311AFBCA329DB28A657A5053A48E3D6F44DD4B78");
        json.put("deviceName", "OCE-AN10");
        json.put("emuiVer", "EmotionUI_12.0.0");
        json.put("ext", "");
        json.put("language", "zh");
        json.put("net", "other");
        json.put("osType", "android");
        json.put("osVer", "2.0.0");
        json.put("photo", picBase64);
        json.put("romVer", "OCE-AN10 2.0.0.268(C00E230R7P3)");
        json.put("time", new Date().getTime());
        json.put("timeZone", "GMT+08:00");
        return json;
    }

    /**
     * 解析图片
     * @param image 图片对象
     * @return
     * @throws IOException
     */
    public JSONObject parse(BufferedImage image) throws IOException {
        String picBase64 = "";
        float quality = 1.0f;
        do{
            if(picBase64.length() != 0){
                if(picBase64.length() > 1000000){
                    if(quality - 0.5f >0){
                        quality -= 0.5f;
                    }else{
                        quality -= 0.25f;
                    }
                }else{
                    if(quality - 0.1f >0){
                        quality -= 0.1f;
                    }else{
                        quality -= 0.05f;
                    }
                }
                if(quality <= 0 ){
                    throw new RuntimeException("画质过大！");
                }
            }

            //如果转码后长度大于307200，则自动降画质，并重新转码
            byte[] bytes = ImageUtil.converterType("jpg", quality, image);
            picBase64 = ImageUtil.toBase64(bytes);
            System.out.println(quality);
            System.out.println(picBase64.length());
        }while (picBase64.length() > 307200);

        StringEntity entity = new StringEntity(productBody(picBase64, image.getWidth(), image.getHeight()).toString());
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        String result = EntityUtils.toString(responseEntity);
        return (JSONObject) JSONObject.parse(result);
    }

    public static Map<String,String> huaweiOcrGetName(MultipartFile imgUrl ,String type) {
        Map<String,String> map = new HashMap<>();
        HuaweiOcr huaweiOcr = new HuaweiOcr();
//        String imgUrl = "C:\\Users\\Siguor\\Desktop\\3333.jpg";
//        parse = huaweiOcr.parse(ImageIO.read(new File(imgUrl));
        JSONObject parse = null;
        try {
            @Cleanup
            InputStream inputStream = imgUrl.getInputStream();
            BufferedImage read = ImageIO.read(inputStream);
            parse = huaweiOcr.parse(read);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MailException("解读图片异常");
        }
        String o = ((JSONObject) ((JSONObject) parse.get("abilityResult")).get("ocrText")).get("value").toString();
        System.out.println(o);
        o=o.trim().replaceAll(" ", "");
        if("1".equals(type)){
            if(o.contains("身份号码")){
                String idNo = StrUtil.subAfter(o,"身份号码",true);
                String name = StrUtil.subBetween(o,"姓名","性别");
                String address = StrUtil.subBetween(o,"住址","公民");
                String nation = StrUtil.subBetween(o,"民族","出生");
                String sex = StrUtil.subBetween(o,"性别","民族");
                String age = StrUtil.subBetween(o,"出生","住址");
                map.put("idNo",idNo);
                map.put("name",name);
                map.put("address",address);
                map.put("nation",nation);
                map.put("sex",sex);
                map.put("age",age);
                System.out.println("证件号："+ idNo);
                System.out.println("姓名："+name);
            }else{
                throw new MailException("请选择身份证图片");
            }
        }
        if("2".equals(type)){
            if(o.contains("银行")){
                Pattern p = Pattern.compile("4|6+[0-9]{15,18}");
                Matcher m = p.matcher(o);
                if (m.find()) {
                    map.put("cardNo",m.group());
                    System.out.println("卡号："+m.group());
                }
            }else{
                throw new MailException("请选择银行卡图片");
            }
        }
        return map;
    }

}
